package org.rcy.framework.mq.converter;

import com.rabbitmq.client.AMQP;
import org.rcy.framework.api.mq.AbstractMessage;
import org.rcy.framework.mq.serializer.MessageSerializer;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter;
import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.util.Date;


/**
 * @author 吴康桥
 * @Description
 * @date 2022/11/11 16:16
 */


public class RabbitMqMessageConverter implements MessageConverter {
	private MessagePropertiesConverter propertiesConverter = new DefaultMessagePropertiesConverter();

	public RabbitMqMessageConverter() {
	}
	@Override
	public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
		try {
			AbstractMessage message = (AbstractMessage)o;
			byte[] body = MessageSerializer.serialize(message);
			return MessageBuilder
					.withBody(body)
					.setContentType(message.getContentType())
					.setType(message.getType())
					.setTimestamp(new Date())
					.setPriority(0)
					.setDeliveryMode(MessageDeliveryMode.PERSISTENT)
					.setContentEncoding("UTF-8")
					.build();
		}catch (Exception e){
			throw new MessageConversionException(e.getMessage());
		}

	}


	@Override
	public Object fromMessage(Message message) throws MessageConversionException {
		try {
			MessageProperties props = message.getMessageProperties();
			AMQP.BasicProperties properties = this.propertiesConverter.fromMessageProperties(props,"UTF-8");
			return 	MessageSerializer.deserialize(message.getBody(),properties);
		}catch (Exception e){
			throw new MessageConversionException(e.getMessage());
		}
	}
}
